//
//  deskModelViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/9.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPProductModeViewController.h"
#import "BPProductInfoViewController.h"
#import "ProductListCell.h"
#import "CycleScrollView.h"
#import "BPProducts.h"
#import "BPImageTool.h"
#import "BPProductTool.h"
#import "BPhttpTool.h"
#import "MJExtension.h"


@interface BPProductModeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic ,strong) CycleScrollView *mainScorllView;

@property (nonatomic,strong)NSArray *productArray;

@property (nonatomic,strong)NSArray *adArry;

@property (nonatomic,assign)NSString *topAD;

/** 头部UIView */
@property (nonatomic ,strong) UIView *ADView;
@end

@implementation BPProductModeViewController


- (void)viewWillAppear:(BOOL)animated{

    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

// 隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpNav];
    
    [self setUpBaseData];

    [self setUpModelList];
    
    [self createButton];
}


// 创建 返回按钮
- (void)createButton{
    
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:button];

    
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 23, 23)];
//    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    UIButton *buttonHomeBig = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 25, 50, 50)];
    buttonHomeBig.backgroundColor = [UIColor clearColor];
    [buttonHomeBig addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonHomeBig];
    
    UIButton *buttonHome = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [buttonHome setBackgroundImage:[UIImage imageNamed:@"homeLeft02"] forState:UIControlStateNormal];
    [buttonHome addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
    [buttonHomeBig addSubview:buttonHome];
    
}
// 头部的 两个按钮
- (void)button:(UIButton *)b{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)buttonHome:(UIButton *)home{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (void)setUpNav
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = self.VCtitle;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithButtonName:@"首页" tatget:self action:@selector(back)];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setUpBaseData
{
    _productDataManger = [[CoreDateManager alloc] init];
    //获取缓存数据
    _productArray = [_productDataManger productListaddCID:self.urlID];
    //下载网络数据
    _topAD = [NSString stringWithFormat:@"adScrollview%@",self.urlID];
    
    [self downloadData];
}

- (void)downloadData
{
    [BPProductTool productsDataWithClassID:self.urlID success:^(id result) {
        //刷新ui
        _productArray = result;
        [_ModelShow reloadData];
        //更新数据
        [_productDataManger deleteProductListaddCID:self.urlID];
        [_productDataManger insertProductListData:result addCID:self.urlID];
    } failure:^(NSError *error) {
        BPLog(@"网络错误");
    }];
    
    [BPhttpTool get:[NSString stringWithFormat:@"%@appapi/getslide/place/2/cate_id/%@",BPhttp,self.urlID] params:nil success:^(id responseObj) {
        self.adArry = responseObj;
        if (self.adArry != nil) {
            [self setUpHeadAdScrollView:_adArry];
        }
//        NSData *jsondata = [NSJSONSerialization dataWithJSONObject:self.adArry options:NSJSONWritingPrettyPrinted error:nil];
//        NSString *jsonString = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
//        [[NSUserDefaults standardUserDefaults] setObject:jsonString forKey:_topAD];
//        [[NSUserDefaults standardUserDefaults] synchronize];
    } failure:^(NSError *error) {
        BPLog(@"%@",error);
    }];
}

- (void)setUpModelList
{
    
    _ADView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, BPScreenW, 200)];
    _ADView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_ADView];
    
    //    CGFloat adH = 200.0f;
    // 第二个页面 轮播图
    _mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, CGRectGetHeight(_ADView.frame)) animationDuration:3];
    
    [_ADView addSubview:_mainScorllView];
    
    
    
    _cellID = @"cellID";
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _ModelShow = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_ADView.frame), BPScreenW, BPScreenH) collectionViewLayout:layout];
    _ModelShow.delegate = self;
    _ModelShow.dataSource = self;
    _ModelShow.showsVerticalScrollIndicator = NO;
    _ModelShow.backgroundColor = [UIColor clearColor];
    
    [_ModelShow registerClass:[ProductListCell class] forCellWithReuseIdentifier:_cellID];
    [self.view addSubview:_ModelShow];
    
//    _cellID = @"cellID";
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//    _ModelShow = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, BPScreenH) collectionViewLayout:layout];
//    _ModelShow.delegate = self;
//    _ModelShow.dataSource = self;
//    _ModelShow.backgroundColor = [UIColor clearColor];
//    
//    [_ModelShow registerClass:[ProductListCell class] forCellWithReuseIdentifier:_cellID];
//    [self.view addSubview:_ModelShow];
//    
//    CGFloat adH = 200.0f;
//    _mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, adH) animationDuration:3];
//    [_ModelShow addSubview:_mainScorllView];
////    NSString *jsonString = [[NSUserDefaults standardUserDefaults] objectForKey:_topAD];
////    if (jsonString != nil) {
////        NSData *jsondata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
////        self.adArry = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments error:nil];
////        [self setUpHeadAdScrollView:_adArry];
////    }
}

- (void)setUpHeadAdScrollView:(NSArray *)topArry
{
    NSMutableArray *viewsArray = [@[] mutableCopy];
    for (NSDictionary *dic in topArry) {
        UIImageView *tempimage = [[UIImageView alloc] initWithFrame:_mainScorllView.bounds];
        [BPImageTool setUpHDImageView:tempimage addNsstringUrl:dic[@"icon"]];
        CGRect viewCg = CGRectMake(0 , _mainScorllView.height - 30, BPScreenW, 30);
        UIView *garyView = [[UIView alloc] initWithFrame:viewCg];
        //设置底部条透明度
        garyView.alpha= 0.5;
        garyView.backgroundColor = BPGlobaBGColor;
        [tempimage addSubview:garyView];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(BPStatusCellInset, tempimage.height - 30, 150, 30.0)];
        if (![dic[@"name"] isKindOfClass:[NSNull class]]) {
            textLabel.textColor = BPGlobaThemeColor;
            textLabel.text = dic[@"name"];
        }
        [tempimage addSubview:textLabel];
        [viewsArray addObject:tempimage];
    }
    
    _mainScorllView.totalPagesCount = ^NSInteger(void){
        return viewsArray.count;
       
    };
    //数据源：获取第pageIndex个位置的contentView（这个必须调）
    _mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    //当点击的时候，执行的block
    __weak typeof(self) weakSelf = self;
    self.mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
        
        BPProductInfoViewController *modelInfo = [[BPProductInfoViewController alloc] init];
        BPProducts *model = [[BPProducts alloc] init];
        NSDictionary *dic = weakSelf.adArry[pageIndex];
        //NSLog(@"%@",dic);
        model.iD = dic[@"pid"];
        model.title = dic[@"name"];
        
        modelInfo.prodectInfo = model;
        modelInfo.leftNavButton = weakSelf.VCtitle;
        [weakSelf.navigationController pushViewController:modelInfo animated:YES];
        
        
    };
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_productArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ProductListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_cellID forIndexPath:indexPath];
    BPProducts *info = _productArray[indexPath.row];
    [BPImageTool setUpUIImageView:cell.listImageView addNsstringUrl:info.cover];
    cell.listPrompt.text = info.title;
    cell.pagesYe.text = [NSString stringWithFormat:@"P%@",info.pagetotal];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BPProductInfoViewController *modelInfo = [[BPProductInfoViewController alloc] init];
    BPProducts *model = _productArray[indexPath.row];
    modelInfo.prodectInfo = model;
    modelInfo.leftNavButton = self.VCtitle;
    [self.navigationController pushViewController:modelInfo animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellW = (BPScreenW - BPStatusCellInset * 3) / 2.0f;
    CGFloat cellH = cellW + 17.0f;
    return CGSizeMake(cellW, cellH);
}

//左右两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return BPStatusCellInset;
}
//上下两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return BPStatusCellInset;
}

// 整个collectionview离边界的大小
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//    return UIEdgeInsetsMake(_mainScorllView.height + BPStatusCellInset, BPStatusCellInset, BPStatusCellInset, BPStatusCellInset);
    return UIEdgeInsetsMake( BPStatusCellInset, BPStatusCellInset, BPStatusCellInset + CGRectGetHeight(_ADView.frame), BPStatusCellInset );
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
